package com.ark.security.service;

import com.ark.common.constant.Constants;
import com.ark.common.domain.entity.sys.SysUser;
import com.ark.common.domain.model.RegisterBody;
import com.ark.common.exception.ServiceException;
import com.ark.common.response.Result;
import com.ark.common.utils.EncryptionUtils;
import com.ark.common.utils.RedisUtils;
import com.ark.common.utils.SecurityUtils;
import com.ark.service.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class RegisterService {

    @Resource
    private MailService mailService;
    @Resource
    private SysUserService userService;
    @Resource
    private RedisUtils redisUtils;

    /**
     * 注册用户
     * @param registerBody 注册信息
     */
    public boolean register(RegisterBody registerBody) {
        if (userService.checkUserNameUnique(registerBody.getUsername())) {
            throw  new ServiceException(Result.error("用户已注册"));
        }else if (userService.emailExist(registerBody.getEmail())) {
            throw  new ServiceException(Result.error("邮箱已被注册"));
        }else if (!StringUtils.isNotEmpty(registerBody.getCode())){
            throw  new ServiceException(Result.error("验证码不能为空"));
        }else if (!ObjectUtils.isNotEmpty(redisUtils.getCacheObject(Constants.REGISTER_USER_KEY+registerBody.getEmail()))
                && !registerBody.getCode().equals(redisUtils.getCacheObject(Constants.REGISTER_USER_KEY+registerBody.getEmail()))){
            throw  new ServiceException(Result.error("验证码错误"));
        }
        SysUser user = new SysUser();
        user.setNickname(registerBody.getUsername());
        user.setUsername(registerBody.getUsername());
        user.setPassword(SecurityUtils.encrypt(registerBody.getPassword()));
        user.setEmail(registerBody.getEmail());
        boolean result= userService.insertUser(user);
        if (result) {
            //邮箱通知账号注册成功
            mailService.sendHtmlTextMailNotice(registerBody.getEmail(), registerBody.getUsername(), registerBody.getPassword());
            //删除验证码
            redisUtils.deleteObject(Constants.REGISTER_USER_KEY+registerBody.getEmail());
            return true;
        }else {
            throw  new ServiceException(Result.error("注册失败"));
        }
    }
}
